import WebSocket, { createWebSocketStream } from 'ws';
import { WSHEADERCLIENTID, getClientId } from './utils.js';
import { MessageObserver } from 'requester-utils/be/protocol.js';
import got from 'got';
import { Readable } from 'node:stream';

const wsServer = "ws://localhost:8081/";
const localServicePort = 8082;

const ws = new WebSocket(wsServer, {
    headers: {
        [WSHEADERCLIENTID]: getClientId()
    }
});
const duplex = createWebSocketStream(ws);
duplex.on('error', console.error);

const observer = MessageObserver.form({ readable: duplex, writable: duplex });
observer.subscribe('request', ({ url, method, headers, body }) => {
    return new Promise((resolve, reject) => {
        const ops = {
            method,
            headers,
        };
        if (method !== 'get' && method != 'head') {
            ops.body = body;
        }
        console.log('===>', `http://localhost:${localServicePort}${url}`)
        const readStream = got.stream(`http://localhost:${localServicePort}${url}`, ops);
        readStream.on('response', async response => {
            resolve({
                headers: response.headers,
                status: response.statusCode,
                stream: readStream
            });
        });
        readStream.once('error', e => {
            let status = 500;
            if (e.code === 'ERR_NON_2XX_3XX_RESPONSE') {
                status = e.message.match(/[0-9]{3}/)[0] || 500;
            }
            resolve({
                status,
                headers: {},
                stream: Readable.from('')
            });
        });
    });
});